package com.cc;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;

public class KeywordAssistant extends JFrame {
    private final JTextField searchField;
    private final DefaultListModel<String> listModel;
    private final JList<String> resultList;
    private String lastSearch = "";
    //备忘录路径
    private final String FILE_PATH = "F://User//备忘录.txt";

    public KeywordAssistant() {
    	//工具名称、版本
        setTitle("KEYWORD ASSISTANT V1.0.50616");
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
 
        // 窗口状态监听
        addWindowStateListener(e -> {
            if ((e.getNewState() & Frame.ICONIFIED) != 0) {
                minimizeToTray();
            }
        });

        // 搜索框
        searchField = new JTextField();
        searchField.getDocument().addDocumentListener(new SearchListener());
        add(searchField, BorderLayout.NORTH);

        // 结果列表
        listModel = new DefaultListModel<>();
        resultList = new JList<>(listModel);
        resultList.setCellRenderer(new HighlightRenderer());
        add(new JScrollPane(resultList), BorderLayout.CENTER);
        
     // 添加按钮到搜索框右侧
        JPanel northPanel = new JPanel(new BorderLayout());
        northPanel.add(searchField, BorderLayout.CENTER);
        
        JButton addButton = new JButton("添加");
        addButton.addActionListener(e -> addToFile());
        northPanel.add(addButton, BorderLayout.EAST);
        
        add(northPanel, BorderLayout.NORTH);
 
        // 添加双击复制功能
        resultList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    handleDoubleClick();
                }
            }
        });
    }
    
 // 新增：添加内容到文件
    private void addToFile() {
        String text = searchField.getText().trim();
        if (text.isEmpty()) {
//            JOptionPane.showMessageDialog(this, "输入内容不能为空", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
 
        try {
            // 使用追加模式写入文件
            Files.write(
                Paths.get(FILE_PATH),
                (System.lineSeparator() + text).getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.APPEND,
                StandardOpenOption.CREATE
            );
            
            searchField.setText(""); // 清空输入框
            JOptionPane.showMessageDialog(this, "内容已成功添加", "提示", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, 
                "文件写入失败: " + ex.getMessage(),
                "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
 
    // 新增：处理双击事件
    private void handleDoubleClick() {
        String selectedText = resultList.getSelectedValue();
        if (selectedText != null) {
        	String[] keyLine = selectedText.split("\\(");
        	if(keyLine.length > 1) {
        		// 复制原始文本（不含HTML标签）
                StringSelection selection = new StringSelection(keyLine[0]);
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                clipboard.setContents(selection, null);
        	}else {
                // 显示复制提示
              JOptionPane.showMessageDialog(this, 
                  "内容异常(" + selectedText + ")", 
                  "错误提示", 
                  JOptionPane.INFORMATION_MESSAGE);
        	}
        }
    }

    private class SearchListener implements DocumentListener {
        @Override
        public void insertUpdate(DocumentEvent e) {
            search();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            search();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            search();
        }
        // 搜索
        private void search() {
            String keyword = searchField.getText().trim();
            if (keyword.equals(lastSearch)) return;
            lastSearch = keyword;

            SwingUtilities.invokeLater(() -> {
                try {
                    List<String> lines = Files.lines(Paths.get(FILE_PATH))
                            .filter(line -> line.toLowerCase().contains(keyword.toLowerCase()))
                            .collect(Collectors.toList());

                    listModel.clear();
                    for (String line : lines) {
                        listModel.addElement(line);
                    }
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(KeywordAssistant.this, 
                            "文件读取失败: " + ex.getMessage(),
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            });
        }
    }

    private class HighlightRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value,
                                                      int index, boolean isSelected, boolean cellHasFocus) {
            Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (c instanceof JLabel && lastSearch.length() > 0) {
                String text = value.toString();
                String highlighted = text.replaceAll(
                        "(" + lastSearch + ")", 
                        "<font color='red'>$1</font>"
                );
                ((JLabel) c).setText("<html>" + highlighted + "</html>");
            }
            return c;
        }
    }

	static TrayIcon trayIcon;
    static SystemTray tray;
    static KeywordAssistant frame;
    
    public static void main(String[] args) {
    	// 检查系统托盘支持
        if (!SystemTray.isSupported()) {
            System.out.println("系统不支持托盘功能");
            return;
        }
        
        SwingUtilities.invokeLater(() -> {
            frame = new KeywordAssistant();
            
            // 获取屏幕尺寸和窗口尺寸
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = frame.getSize();
            
            // 计算位置：屏幕宽度 - 窗口宽度，Y坐标为0
            int x = screenSize.width - frameSize.width;
            int y = 0;
            
            // 设置窗口位置
            frame.setLocation(x, y);
            frame.setVisible(true);
        });
    }
 
    private void setupTrayIcon() {
        // 获取系统托盘实例
        tray = SystemTray.getSystemTray();
 
        // 创建弹出菜单
        PopupMenu popup = new PopupMenu();
        MenuItem openItem = new MenuItem("open");
        MenuItem exitItem = new MenuItem("exit");
 
        // 添加菜单项事件
        openItem.addActionListener(e -> restoreFrame());
        exitItem.addActionListener(e -> System.exit(0));
 
        popup.add(openItem);
        popup.addSeparator();
        popup.add(exitItem);
 
        // 创建托盘图标（使用默认图标，实际应替换为16x16图片）
        Image image = Toolkit.getDefaultToolkit().getImage("keyword-assistant-16.png");
		try {
			image = ImageIO.read(new File("keyword-assistant-16.png"));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

        // 替换为您的图标路径
        trayIcon = new TrayIcon(image, "KA", popup);
 
        // 设置托盘图标鼠标事件
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    restoreFrame();
                }
            }
        });
 
        try {
        tray.add(trayIcon);
    } catch (AWTException ex) {
        ex.printStackTrace();
    }
}
 
    private void minimizeToTray() {
        if (!frame.isVisible()) return;
 
        frame.setVisible(false); // 隐藏主窗口
        setupTrayIcon();
    }
 
    private static void restoreFrame() {
        frame.setVisible(true);
        frame.setState(Frame.NORMAL); // 恢复窗口状态
        tray.remove(trayIcon); // 从托盘移除图标
    }
}